// DOM 元素
const totalClicksEl = document.getElementById('totalClicks');
const dailyClicksEl = document.getElementById('dailyClicks');
const clickHistoryEl = document.getElementById('clickHistory');
const refreshBtn = document.getElementById('refreshBtn');
const resetBtn = document.getElementById('resetBtn');
const viewMoreBtn = document.getElementById('viewMoreBtn');

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    loadStats();

    // 绑定事件
    refreshBtn.addEventListener('click', loadStats);
    resetBtn.addEventListener('click', resetStats);
    viewMoreBtn.addEventListener('click', openHistoryPage);
});

// 加载统计数据
async function loadStats() {
    try {
        // 显示加载状态
        showLoading();

        // 直接从 storage 获取数据，参考 history.js 的实现
        const data = await chrome.storage.local.get(['clickHistory', 'totalClicks', 'dailyClicks']);
        console.log('Raw data from storage:', data);

        const stats = {
            totalClicks: data.totalClicks || 0,
            dailyClicks: data.dailyClicks || 0,
            clickHistory: data.clickHistory || []
        };
        console.log('Processed statistics data:', stats);

        // 更新显示
        updateStats(stats);

    } catch (error) {
        console.error('Failed to load statistics data:', error);
        showError('Failed to load data');
    }
}

// 显示加载状态
function showLoading() {
    // 正确设置加载状态，保持 HTML 结构
    const totalNumberValueEl = totalClicksEl.querySelector('.number-value');
    const dailyNumberValueEl = dailyClicksEl.querySelector('.number-value');

    if (totalNumberValueEl) totalNumberValueEl.textContent = '...';
    if (dailyNumberValueEl) dailyNumberValueEl.textContent = '...';
    clickHistoryEl.innerHTML = '<div class="loading">Loading...</div>';
}

// 更新统计显示
function updateStats(stats) {
    console.log('Updating statistics display with data:', stats);

    // 更新数字显示
    animateNumber(totalClicksEl, stats.totalClicks);
    animateNumber(dailyClicksEl, stats.dailyClicks);

    // 更新点击历史
    updateClickHistory(stats.clickHistory);
}

// 数字动画效果
function animateNumber(element, targetNumber) {
    const numberValueEl = element.querySelector('.number-value');
    if (!numberValueEl) {
        console.warn('Could not find .number-value element, setting number directly', element, targetNumber);
        // 如果找不到 .number-value 元素，直接设置到父元素
        element.textContent = targetNumber;
        return;
    }

    const currentNumber = parseInt(numberValueEl.textContent) || 0;

    // 如果目标数字相同，直接设置
    if (currentNumber === targetNumber) {
        numberValueEl.textContent = targetNumber;
        return;
    }

    const increment = Math.ceil(Math.abs(targetNumber - currentNumber) / 20);

    if (currentNumber < targetNumber) {
        numberValueEl.textContent = Math.min(currentNumber + increment, targetNumber);
        setTimeout(() => animateNumber(element, targetNumber), 50);
    } else if (currentNumber > targetNumber) {
        numberValueEl.textContent = Math.max(currentNumber - increment, targetNumber);
        setTimeout(() => animateNumber(element, targetNumber), 50);
    } else {
        numberValueEl.textContent = targetNumber;
    }
}

// 更新点击历史
function updateClickHistory(history) {
    if (!history || history.length === 0) {
        clickHistoryEl.innerHTML = '<div class="no-data">No click records yet</div>';
        return;
    }

    // 只显示最近 10 次点击
    const recentHistory = history.slice(0, 10);
    const historyHTML = recentHistory.map((click, index) => {
                const time = new Date(click.timestamp).toLocaleTimeString('en-US', {
                    hour12: false,
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
                const domain = new URL(click.url).hostname;

                return `
            <div class="history-item" style="animation-delay: ${index * 0.1}s">
                <div class="history-time">${time}</div>
                <div class="history-details">
                    <div class="history-domain">${domain}</div>
                    <div class="history-element">${click.element.selector}</div>
                    ${click.element.text ? `<div class="history-text">"${escapeHtml(click.element.text)}"</div>` : ''}
                </div>
                <div class="history-position">(${click.x}, ${click.y})</div>
            </div>
        `;
    }).join('');
    
    clickHistoryEl.innerHTML = historyHTML;
}

// 重置统计数据
async function resetStats() {
    if (!confirm('Are you sure you want to reset all statistics data? This action cannot be undone.')) {
        return;
    }
    
    try {
        resetBtn.textContent = 'Resetting...';
        resetBtn.disabled = true;
        
        await sendMessage({ action: 'resetStats' });
        
        // 重新加载数据
        await loadStats();
        
        showSuccess('Statistics data has been reset');
        
    } catch (error) {
        console.error('Failed to reset statistics data:', error);
        showError('Reset failed');
    } finally {
        resetBtn.textContent = 'Reset Statistics';
        resetBtn.disabled = false;
    }
}

// 发送消息到后台脚本
function sendMessage(message) {
    return new Promise((resolve, reject) => {
        chrome.runtime.sendMessage(message, (response) => {
            if (chrome.runtime.lastError) {
                reject(chrome.runtime.lastError);
            } else {
                resolve(response);
            }
        });
    });
}

// 显示成功消息
function showSuccess(message) {
    showNotification(message, 'success');
}

// 显示错误消息
function showError(message) {
    showNotification(message, 'error');
}

// 显示通知
function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    // 自动移除通知
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// 格式化大数字
function formatNumber(num) {
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
    }
    return num.toString();
}

// HTML 转义函数，防止 XSS
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 添加键盘快捷键支持
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + R：刷新数据
    if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
        e.preventDefault();
        loadStats();
    }
    
    // ESC：关闭 popup
    if (e.key === 'Escape') {
        window.close();
    }
});

// 添加页面可见性 API 支持，当页面变为可见时自动刷新
document.addEventListener('visibilitychange', function() {
    if (!document.hidden) {
        loadStats();
    }
});

// 打开历史详情页面
function openHistoryPage() {
    // 使用 chrome.tabs API 在新标签页中打开历史页面
    chrome.tabs.create({
        url: chrome.runtime.getURL('history.html')
    });
}